package cn.b.sky.user.controller;

import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.model.TreeInterface;
import cn.b.sky.i18n.enums.LocaleResourceEnum;
import cn.b.sky.i18n.service.I18nService;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.service.LoginLogService;
import cn.b.sky.user.service.MenuService;
import cn.b.sky.user.service.UserService;
import cn.b.sky.user.service.model.Language;
import cn.b.sky.user.service.model.Menu;
import cn.b.sky.user.service.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.janino.Mod;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * <strong>Title : HostController.java<br>
 * </strong> <strong>Package : cn.b.sky.user.controller<br>
 * </strong> <strong>Description : </strong>应用入口控制器<br>
 * <strong>Create on : 2015-5-25 下午2:16:11<br>
 * </strong>
 * <p>
 * 
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 *          <strong>修改历史:</strong><br>
 *          修改人 | 修改日期 | 修改描述<br>
 *          -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "/*")
@Slf4j
public class HostController extends SecurityController {
  @Resource
  private UserService userService;

  @Resource
  private MenuService menuService;

  @Resource
  private I18nService i18nService;

  @Resource
  private LoginLogService loginLogService;

  @RequestMapping(value = "index")
  public String hostPlatform(Model model, HttpSession session) {
    try {
      UserInfo user = SecurityContextUtil.getCurrentUser();
      if (session.getAttribute("menuTrees") == null) {
        String userName = user.getUsername();
        List<Menu> menus = new ArrayList<Menu>();
        if(user.isAdministrator()){
          menus.addAll(menuService.getCurrentSiteMenus(this.getSiteCode(), this.getCurrentLanguage()));
        }else{
          menus.addAll(menuService.getCurrentUserMenus(userName, this.getCurrentLanguage()));
        }
        List<TreeInterface> trees = menuService.gradingRecursion(menus.toArray(new Menu[menus.size()]), null);
        session.setAttribute("menuTrees", trees);
      }
      model.addAttribute("userName", user.getUserText());
      model.addAttribute("siteCode", user.getSiteCode());
      model.addAttribute("language", user.getLanguageCode());
      session.setAttribute("timeZone", user.getJavaTimeZoneId());
      //缓存不存在则加载，第一次登陆加载
      if(LocaleResourceBundle.getBundle(this.getSiteCode(),
          LocaleResourceEnum.COMMONRESOURCES.getValue(), this.getCurrentLanguage()) == null) {
        i18nService.flushLocaleResourceBundleByLanguage(this.getSiteCode(), this.getCurrentLanguage());
      }
    } catch (Exception e) {
      log.error("{}", e);
    }
    return "index";
  }

  /**
   * 
   * <strong>Title : getResourcesAndAuthorities<br></strong>
   * <strong>Description : </strong>获取国际化资源以及用户权限<br> 
   * <strong>Create on : 2016年7月6日 下午12:33:01<br></strong>
   * <p>
   * @param siteCode
   * @param languageCode
   * @return
   * Map<String,Object>
   * @throws 
   * @author Yantao.Lu<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   * <strong>修改历史:</strong><br>
   * 修改人 | 修改日期 | 修改描述<br>
   * -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "getResourcesAndAuthorities")
  @ResponseBody
  public Map<String, Object> getResourcesAndAuthorities(String siteCode, String languageCode) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("CommonResources",
        LocaleResourceBundle.getBundle(siteCode, LocaleResourceEnum.COMMONRESOURCES.getValue(), languageCode).getResources());
    map.put("ButtonAuthorities", SecurityContextUtil.getCurrentUser().getButtonAuthorities());
    return map;
  }

  @RequestMapping(value = "login", method = RequestMethod.GET)
  public String login(Model model, String error, HttpSession session) {
    if (!StringUtils.isBlank(error)) {
      Exception exception = (Exception) session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
      if(exception instanceof AuthenticationException){
        model.addAttribute("message", exception.getMessage());
      }else{
        model.addAttribute("message", "用户名，工厂代码或密码错误！");
      }
    }
    UserInfo user = SecurityContextUtil.getCurrentUser(session);
    if (user != null && !StringUtils.isBlank(user.getUserCode())) {
      return "redirect:/manage/index";
    }
    // 登陆页面加载登陆的国际化语言包
    List<Language> languages = userService.selectAllLanaguage();
    model.addAttribute("languages", languages);
    return "login";
  }

  /**
   * 
   * <strong>Title : loginOut<br>
   * </strong> <strong>Description : </strong>用户登出记录日志<br>
   * <strong>Create on : 2015-8-31 下午1:54:00<br>
   * </strong>
   * <p>
   * 
   * @param model
   * @return String
   * @throws
   * @author lidapeng<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   *          <strong>修改历史:</strong><br>
   *          修改人 | 修改日期 | 修改描述<br>
   *          -------------------------------------------<br>
   * <br>
   * <br>
   */
  @RequestMapping(value = "mylogout", method = RequestMethod.GET)
  public String loginOut(Model model, HttpSession session) {
    if (session != null) {
      String sessionId = session.getId();
      // 修改退出时间
      loginLogService.modifyLoginLog(sessionId);
    }
    return "redirect:/manage/logout";
  }

  /**
   * 
   * <strong>Title : menuList<br>
   * </strong> <strong>Description : </strong>获取用户菜单权限<br>
   * <strong>Create on : 2014-2-25 下午05:08:18<br>
   * </strong>
   * <p>
   * 
   * @return DWZResult
   * @throws
   * @author dapeng_li<br>
   * @version <strong>v1.0.0</strong><br>
   * <br>
   *          <strong>修改历史:</strong><br>
   *          修改人 | 修改日期 | 修改描述<br>
   *          -------------------------------------------<br>
   * <br>
   * <br>
   */
  @ResponseBody
  @RequestMapping(value = "menuList", method = RequestMethod.POST)
  public DWZResult menuList() {
    return null;
  }

  @RequestMapping("accessDenied")
  public String accessDenied(Model model) {

    return "/error/accessDenied";
  }

  @RequestMapping(value = "changePWD", method = RequestMethod.GET)
  public String changePWD(Model model) {

    return "user/changepwd";
  }
}
